﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using CSharp.Libs.WPF;
using CSharp.Libs.ExceptionHandling;
using CSharp.Libs.Koc;
//using KocMapView;
using System.Collections;
using System.Windows.Media;
using AutoKoC.Models;
using AutoKoC.ViewModels.ItemClasses;
using System.Windows.Input;


namespace AutoKoC.ViewModels
{
    class AllianceComparerViewModel : ViewModelBase
    {
        #region declarations
        private AppBase _AB = null;

        private RelayCommand _rcShowMap = null;

        //private wndKocMapView _KMV = null;

        //private ObservableCollection<AllianceComparerListItem> _ocAllianceCompareList = new ObservableCollection<AllianceComparerListItem>();
        private ArrayList _aryKoordItems = new ArrayList();
        private SolidColorBrush[] _scbDefinedBrushes = new SolidColorBrush[10];

        private Boolean _fExecuteViewCourt = false;

        #region constants
        private const String DATE_TIME_STAMP_MASK =         "dd.MM.yyyy HH:mm:ss";

        private const String OLD_PARAM_PAGE_NO =            "pageNo";
        private const String OLD_PARAM_CITY_ID =            "cityId";

        private const String PARAM_PER_PAGE =               "perPage";
        private const String PARAM_ALLIANCE_ID =            "allianceId";

        private const String PARAM_PID =                    "pid";

        private const String PARAM_CHECK_ARR =              "checkArr";

        //private const String KEY_OK =                       "ok";
        //private const String KEY_RESULTS =                  "results";
        //private const String KEY_ALLIANCE_ID =              "allianceId";
        //private const String KEY_ALLIANCE_NAME =            "allianceName";
        //private const String KEY_RANK =                     "rank";
        //private const String KEY_USER_ID =                  "userId";
        //private const String KEY_DISPLAY_NAME =             "displayName";
        //private const String KEY_PLAYER_SEX =               "playerSex";
        //private const String KEY_AVATAR_ID =                "avatarId";
        //private const String KEY_WAR_STATUS =               "warStatus";
        //private const String KEY_MIGHT =                    "might";
        //private const String KEY_TITLE =                    "title";
        //private const String KEY_OFFICER_TYPE =             "officerType";
        //private const String KEY_NUM_CITIES =               "numCities";
        //private const String KEY_CITIES =                   "cities";
        //private const String KEY_CITY_ID =                  "cityId";
        //private const String KEY_CITY_NAME =                "cityName";
        //private const String KEY_CITY_X_COORD =             "xCoord";
        //private const String KEY_CITY_Y_COORD =             "yCoord";

        //private const String KEY_DAILY_ACTION_FLAG  =       "dailyActionFlag";
        //private const String KEY_PLAYER_INFO =              "playerInfo";
        //private const String KEY_EMAIL =                    "email";
        //private const String KEY_FB_UID =                   "fbuid";
        //private const String KEY_USER_TYPE =                "usertype";
        //private const String KEY_STATUS =                   "status";
        //private const String KEY_DATE_JOINED =              "dateJoined";
        //private const String KEY_LAST_LOGIN =               "lastLogin";
        //private const String KEY_EVENT_TIMESTAMP =          "eventTimestamp";
        //private const String KEY_EVENT_STATUS =             "eventStatus";
        //private const String KEY_TRUCE_EXPIRE_TIMESTAMP =   "truceExpireTimestamp";
        //private const String KEY_FOG_EXPIRE_TIMESTAMP =     "fogExpireTimestamp";
        //private const String KEY_CNT_NEWMSG =               "cnt_newmsg";
        //private const String KEY_CNT_FRIENDREQ =            "cnt_friendreq";
        //private const String KEY_CNT_LOGINS =               "cnt_logins";
        //private const String KEY_CNT_PASSRESET =            "cnt_passreset";
        //private const String KEY_CNT_CONNECTIONS =          "cnt_connections";
        //private const String KEY_PHOTO_HOST =               "photo_host";
        //private const String KEY_PHOTO_DIR =                "photo_dir";
        //private const String KEY_PHOTO_SUBDIR =             "photo_subdir";
        //private const String KEY_PHOTO_NAME =               "photo_name";

        //private const String KEY_DATA =                     "data";
        #endregion
        #endregion



        #region constructor / terminator
        public AllianceComparerViewModel(
            AppBase AB)
        {
            _AB = AB;
            
            _scbDefinedBrushes[0] = Brushes.Red;
            _scbDefinedBrushes[1] = Brushes.Blue;
            _scbDefinedBrushes[2] = Brushes.Green;
            _scbDefinedBrushes[3] = Brushes.Black;
            _scbDefinedBrushes[4] = Brushes.Magenta;
            _scbDefinedBrushes[5] = Brushes.Cyan;
            _scbDefinedBrushes[6] = Brushes.Wheat;
            _scbDefinedBrushes[7] = Brushes.Brown;
            _scbDefinedBrushes[8] = Brushes.Yellow;
            _scbDefinedBrushes[9] = Brushes.DarkGray;

            //_ocAllianceCompareList.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(_ocAllianceCompareList_CollectionChanged);
        }

        ~AllianceComparerViewModel()
        {
            //_ocAllianceCompareList.CollectionChanged -= _ocAllianceCompareList_CollectionChanged;
            //_ocAllianceCompareList = null;

            _AB = null;
        }
        #endregion



        #region eventhandling
        void _ocAllianceCompareList_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            //Int32 IDX = 0;

            //foreach (AllianceComparerListItem ACLI in _ocAllianceCompareList)
            //{
            //    if(IDX > _scbDefinedBrushes.GetUpperBound(0))
            //    {
            //        ACLI.Color = _scbDefinedBrushes[0];
            //    }
            //    else
            //    {
            //        ACLI.Color = _scbDefinedBrushes[IDX++];
            //    }
            //}
        }
        #endregion



        #region private functions
        /// <summary>_PreparePhpCommands
        /// 
        /// </summary>
        private void _PreparePhpCommands()
        {
            try
            {
                if(!_AB.UH.URLAllianceGetOtherInfo.URLMaybeValid)
                {
                    //Generate Command (without own parameters -> myServers.php) out of getChat.php
                    _AB.UH.ParseURLAllianceGetOtherInfo(_AB.UH.URLGetChat.GetURL().Replace(URLHolder.PHP_GET_CHAT, URLHolder.PHP_ALLIANCE_GET_OTHER_INFO));

                    //Remove getChat.php specific parameters
                    _AB.UH.URLAllianceGetOtherInfo.Parameters.Remove(URLHolder.PARAM_CTYPE);
                    _AB.UH.URLAllianceGetOtherInfo.Parameters.Remove(URLHolder.PARAM_CTYPE_ID);
                    _AB.UH.URLAllianceGetOtherInfo.Parameters.Remove(URLHolder.PARAM_CUR_NEWEST_1);
                    _AB.UH.URLAllianceGetOtherInfo.Parameters.Remove(URLHolder.PARAM_CUR_NEWEST_2);
                    _AB.UH.URLAllianceGetOtherInfo.Parameters.Remove(URLHolder.PARAM_CUR_NEWEST_3);
                    _AB.UH.URLAllianceGetOtherInfo.Parameters.Remove(URLHolder.PARAM_SID);

                    //Add allianceGetOtherInfo specific parameters
                    String strCityID = "";
                    if(_AB.BSVM.Cities.Count > 0)
                    {
                        strCityID = _AB.BSVM.Cities[0].CityID.ToString();
                    }
                    _AB.UH.URLAllianceGetOtherInfo.Parameters.Add(URLHolder.PARAM_CITY_ID, strCityID);
                    _AB.UH.URLAllianceGetOtherInfo.Parameters.Add(URLHolder.PARAM_PAGE_NO, "1");
                }

                if (_AB.UH.URLAllianceGetOtherInfo.URLMaybeValid)
                {
                    if (!_AB.UH.URLGetUserLeaderboard.URLMaybeValid)
                    {
                        _AB.UH.ParseURLGetUserLeaderboard(_AB.UH.URLAllianceGetOtherInfo.GetURL().Replace(URLHolder.PHP_ALLIANCE_GET_OTHER_INFO, URLHolder.PHP_GET_USER_LEADERBOARD));
                        _AB.UH.URLGetUserLeaderboard.Parameters.Remove(URLHolder.PARAM_PAGE_NO);
                        _AB.UH.URLGetUserLeaderboard.Parameters.Remove(URLHolder.PARAM_CITY_ID);
                        _AB.UH.URLGetUserLeaderboard.Parameters.Add(URLHolder.PARAM_ALLIANCE_ID, "");
                        _AB.UH.URLGetUserLeaderboard.Parameters.Add(URLHolder.PARAM_PER_PAGE, 100.ToString());
                    }

                    if (!_AB.UH.URLViewCourt.URLMaybeValid)
                    {
                        _AB.UH.ParseURLViewCourt(_AB.UH.URLAllianceGetOtherInfo.GetURL().Replace(URLHolder.PHP_ALLIANCE_GET_OTHER_INFO, URLHolder.PHP_VIEW_COURT));
                        _AB.UH.URLViewCourt.Parameters.Remove(URLHolder.PARAM_PAGE_NO);
                        _AB.UH.URLViewCourt.Parameters.Remove(URLHolder.PARAM_CITY_ID);
                        _AB.UH.URLViewCourt.Parameters.Add(URLHolder.PARAM_PID, "");
                    }

                    if (!_AB.UH.URLGetOnline.URLMaybeValid)
                    {
                        _AB.UH.ParseURLGetOnline(_AB.UH.URLAllianceGetOtherInfo.GetURL().Replace(URLHolder.PHP_ALLIANCE_GET_OTHER_INFO, URLHolder.PHP_GET_ONLINE));
                        _AB.UH.URLGetOnline.Parameters.Remove(URLHolder.PARAM_PAGE_NO);
                        _AB.UH.URLGetOnline.Parameters.Remove(URLHolder.PARAM_CITY_ID);
                        _AB.UH.URLViewCourt.Parameters.Add(URLHolder.PARAM_CHECK_ARR, "");
                    }
                }
                else
                {
                    _AB.EC.AddException(new ArgumentException("Parent URL is not valid."), this.ToString(), _AB.EC.Tools.GetCurrentMethodName());
                }
            }
            catch(Exception ex)
            {
                _AB.EC.AddException(ex, this.ToString(), _AB.EC.Tools.GetCurrentMethodName());
                throw;
            }
        }

        private void _SetUrl(
            String AllianceId)
        {
            try
            {
                if (_AB.UH.URLAllianceGetOtherInfo.URLMaybeValid)
                {
                    if(!_AB.UH.URLGetUserLeaderboard.URLMaybeValid)
                    {
                        _AB.UH.ParseURLGetUserLeaderboard(_AB.UH.URLAllianceGetOtherInfo.GetURL().Replace(URLHolder.PHP_ALLIANCE_GET_OTHER_INFO, URLHolder.PHP_GET_USER_LEADERBOARD));
                        _AB.UH.URLGetUserLeaderboard.Parameters.Add(URLHolder.PARAM_ALLIANCE_ID, AllianceId.ToString());
                        _AB.UH.URLGetUserLeaderboard.Parameters.Add(URLHolder.PARAM_PER_PAGE, 100.ToString());
                    }

                    _AB.UH.URLGetUserLeaderboard.Parameters[URLHolder.PARAM_ALLIANCE_ID] = AllianceId.ToString();
                    _AB.UH.URLGetUserLeaderboard.Parameters[URLHolder.PARAM_PER_PAGE] = 100.ToString();
                }
                else
                {
                    _AB.EC.AddException(new ArgumentException("Parent URL is not valid."), this.ToString(), _AB.EC.Tools.GetCurrentMethodName());
                }
            }
            catch(Exception ex)
            {
                _AB.EC.AddException(ex, this.ToString(), _AB.EC.Tools.GetCurrentMethodName());
            }
        }

        /// <summary>_ExecuteURLs
        /// 
        /// </summary>
        /// <param name="ExecuteViewCourt"></param>
        private void _ExecuteURLs()
        {
            try
            {
                //_PreparePhpCommands();

                //if (_AB.UH.URLGetUserLeaderboard.URLMaybeValid)
                //{
                //    _aryKoordItems.Clear();
                //    ArrayList _aryAllianceMembers = new ArrayList();

                //    foreach(AllianceComparerListItem ACLI in _ocAllianceCompareList)
                //    {
                //        _SetUrl(ACLI.AllianceId);

                //        Hashtable htResult = null;
                //        if (_AB.UH.URLGetUserLeaderboard.GetAnswerHashtable(out htResult))
                //        {
                //            Boolean fResultOk = false;
                //            Boolean.TryParse(htResult[constants.KEY_OK].ToString(), out fResultOk);
                //            if(fResultOk)
                //            {
                //                ArrayList _aryResults = htResult[constants.KEY_RESULTS] as ArrayList;
                //                if(_aryResults != null)
                //                {
                //                    String strCheckArr = "";
                //                    Boolean fFirst = true;

                //                    foreach(Hashtable HT in _aryResults)
                //                    {
                //                        try
                //                        {
                //                            KocAllianceMembersListItem KAMLI = new KocAllianceMembersListItem();

                //                            ArrayList aryCities = HT[constants.KEY_CITIES] as ArrayList;
                //                            if(aryCities != null)
                //                            {
                //                                foreach(Hashtable htCity in aryCities)
                //                                {
                //                                    KocAllianceMembersCityItem KAMCI = new KocAllianceMembersCityItem();

                //                                    KAMCI.CityId = htCity[constants.KEY_CITY_ID].ToString();
                //                                    KAMCI.CityName = htCity[constants.KEY_CITY_NAME].ToString();
                //                                    KAMCI.XCoord = htCity[constants.KEY_CITY_X_COORD].ToString();
                //                                    KAMCI.YCoord = htCity[constants.KEY_CITY_Y_COORD].ToString();

                //                                    KAMLI.Cities.Add(KAMCI);
                //                                }
                //                            }

                //                            KAMLI.Color = ACLI.Color;

                //                            KAMLI.AllianceId = htResult[constants.KEY_ALLIANCE_ID].ToString();
                //                            KAMLI.AllianceName = htResult[constants.KEY_ALLIANCE_NAME].ToString();

                //                            KAMLI.Rank = HT[constants.KEY_RANK].ToString();
                //                            KAMLI.UserId = HT[constants.KEY_USER_ID].ToString();
                //                            KAMLI.DisplayName = HT[constants.KEY_DISPLAY_NAME].ToString();
                //                            KAMLI.PlayerSex = HT[constants.KEY_PLAYER_SEX].ToString();
                //                            KAMLI.AvatarId = HT[constants.KEY_AVATAR_ID].ToString();
                //                            KAMLI.WarStatus = HT[constants.KEY_WAR_STATUS].ToString();
                //                            try
                //                            {
                //                                KAMLI.Might = Int32.Parse(HT[constants.KEY_MIGHT].ToString()).ToString("0,000");
                //                            }
                //                            catch
                //                            {
                //                            }
                //                            KAMLI.Title = HT[constants.KEY_TITLE].ToString();
                //                            //KAMLI.OfficerType = HT[KEY_OFFICER_TYPE].ToString();
                //                            switch(HT[constants.KEY_OFFICER_TYPE].ToString())
                //                            {
                //                                case "1":
                //                                    KAMLI.OfficerType = "Chancelor";
                //                                    break;
                //                                case "2":
                //                                    KAMLI.OfficerType = "Vice Chancelor";
                //                                    break;
                //                                case "3":
                //                                    KAMLI.OfficerType = "Officer";
                //                                    break;
                //                                default:
                //                                    KAMLI.OfficerType = "";
                //                                    break;
                //                            }
                //                            KAMLI.NumCities = HT[constants.KEY_NUM_CITIES].ToString();

                //                            //Build CheckArr parameter
                //                            if(fFirst)
                //                            {
                //                                strCheckArr = KAMLI.UserId;
                //                                fFirst = false;
                //                            }
                //                            else
                //                            {
                //                                strCheckArr = String.Concat(strCheckArr, ",", KAMLI.UserId);
                //                            }

                //                            //Get ViewCourt info
                //                            if (_fExecuteViewCourt)
                //                            {
                //                                Hashtable htViewCourt = _GetViewCourt(Int32.Parse(KAMLI.UserId));
                //                                if (htViewCourt != null)
                //                                {
                //                                    Hashtable htPlayerInfo = htViewCourt[constants.KEY_PLAYER_INFO] as Hashtable;
                //                                    if (htPlayerInfo != null)
                //                                    {
                //                                        KAMLI.DailyActionFlag = htViewCourt[constants.KEY_DAILY_ACTION_FLAG].ToString();

                //                                        KAMLI.Email = htPlayerInfo[constants.KEY_EMAIL].ToString();
                //                                        KAMLI.FBUID = htPlayerInfo[constants.KEY_FB_UID].ToString();
                //                                        KAMLI.UserType = htPlayerInfo[constants.KEY_USER_TYPE].ToString();
                //                                        KAMLI.Status = htPlayerInfo[constants.KEY_STATUS].ToString();
                //                                        KAMLI.DateJoined = htPlayerInfo[constants.KEY_DATE_JOINED].ToString();
                //                                        KAMLI.LastLogin = htPlayerInfo[constants.KEY_LAST_LOGIN].ToString();
                //                                        KAMLI.EventTimeStamp = htPlayerInfo[constants.KEY_EVENT_TIMESTAMP].ToString();
                //                                        KAMLI.EventStatus = htPlayerInfo[constants.KEY_EVENT_STATUS].ToString();
                //                                        KAMLI.TruceExpireTimestamp = htPlayerInfo[constants.KEY_TRUCE_EXPIRE_TIMESTAMP].ToString();
                //                                        KAMLI.FogExpireTimestamp = htPlayerInfo[constants.KEY_FOG_EXPIRE_TIMESTAMP].ToString();
                //                                        KAMLI.CntNewMsg = htPlayerInfo[constants.KEY_CNT_NEWMSG].ToString();
                //                                        KAMLI.CntFriendReq = htPlayerInfo[constants.KEY_CNT_FRIENDREQ].ToString();
                //                                        KAMLI.CntLogins = htPlayerInfo[constants.KEY_CNT_LOGINS].ToString();
                //                                        KAMLI.CntPassReset = htPlayerInfo[constants.KEY_CNT_PASSRESET].ToString();
                //                                        KAMLI.CntConnections = htPlayerInfo[constants.KEY_CNT_CONNECTIONS].ToString();
                //                                        //KAMLI.PhotoHost = htPlayerInfo[KEY_PHOTO_HOST].ToString();
                //                                        //KAMLI.PhotoDir = htPlayerInfo[KEY_PHOTO_DIR].ToString();
                //                                        //KAMLI.PhotoSubDir = htPlayerInfo[KEY_PHOTO_SUBDIR].ToString();
                //                                        //KAMLI.PhotoName = htPlayerInfo[KEY_PHOTO_NAME].ToString();
                //                                    }

                //                                }
                //                            }

                //                            _aryAllianceMembers.Add(KAMLI);
                //                        }
                //                        catch(Exception ex)
                //                        {
                //                            _AB.EC.AddException(ex, this.ToString(), _AB.EC.Tools.GetCurrentMethodName());
                //                        }
                //                    }

                //                    //Get Online info
                //                    if(strCheckArr != "")
                //                    {
                //                        _AB.UH.URLGetOnline.Parameters[PARAM_CHECK_ARR] = strCheckArr;

                //                        Hashtable htOnline = null;
                //                        if(_AB.UH.URLGetOnline.GetAnswerHashtable(out htOnline))
                //                        {
                //                            if(htOnline != null)
                //                            {
                //                                fResultOk = false;
                //                                Boolean.TryParse(htOnline[constants.KEY_OK].ToString(), out fResultOk);
                //                                if(fResultOk)
                //                                {
                //                                    Hashtable htData = htOnline[constants.KEY_DATA] as Hashtable;
                //                                    if(htData != null)
                //                                    {
                //                                        foreach(KocAllianceMembersListItem KAMLI in _aryAllianceMembers)
                //                                        {
                //                                            if(htData[KAMLI.UserId] != null &&
                //                                               Boolean.Parse(htData[KAMLI.UserId].ToString()))
                //                                            {
                //                                                KAMLI.Online = "ONLINE";
                //                                            }
                //                                        }
                //                                    }
                //                                }
                //                            }
                //                        }
                //                    }
                //                }
                //                else
                //                {
                //                    //_strResult = "Server didn't return ArrayList.";
                //                }
                //            }
                //            else
                //            {
                //                //_strResult = "Server returned false.";
                //            }
                //        }
                //        else
                //        {
                //            //_strResult = "Execute didn't return true.";
                //        }
                //    }

                //    //Generate KoordItems
                //    foreach (KocAllianceMembersListItem KAMLI in _aryAllianceMembers)
                //    {
                //        foreach (KocAllianceMembersCityItem KAMCI in KAMLI.Cities)
                //        {
                //            try
                //            {
                //                KoordItem KI = new KoordItem(
                //                    KAMCI.XCoord + "," + KAMCI.YCoord,
                //                    KAMLI.DisplayName,
                //                    KAMLI.Might,
                //                    KAMLI.AllianceName,
                //                    KAMCI.CityName,
                //                    KAMLI.Online,
                //                    KAMLI.LastLogin,
                //                    KAMLI.Color);
                                
                //                _aryKoordItems.Add(KI);
                //            }
                //            catch 
                //            {
                //            }
                //        }
                //    }
                //}
                //else
                //{
                //    //_strResult = "URL is not valid.";
                //}
            }
            catch(Exception ex)
            {
                _AB.EC.AddException(ex, this.ToString(), _AB.EC.Tools.GetCurrentMethodName());
            }
        }

        private Hashtable _GetViewCourt(
            Int32 UserId)
        {
            try
            {
                if(UserId > 0)
                {
                    _AB.UH.URLViewCourt.Parameters[PARAM_PID] = UserId.ToString();

                    Hashtable HT=null;
                    _AB.UH.URLViewCourt.GetAnswerHashtable(out HT);

                    if(HT != null)
                    {
                        return HT;
                    }
                }
            }
            catch(Exception ex)
            {
                _AB.EC.AddException(ex, this.ToString(), _AB.EC.Tools.GetCurrentMethodName());
            }

            return null;
        }

        /// <summary>_ShowMap
        /// 
        /// </summary>
        private void _ShowMap()
        {
            try
            {
                _ExecuteURLs();

                //_KMV = new wndKocMapView();
                //KocMapViewViewModel KMVVM = _KMV.DataContext as KocMapViewViewModel;
                //if(KMVVM != null)
                //{
                //    KMVVM.ShowCoords(KoordItems);
                //}

                //_KMV.ShowDialog();
            }
            catch(Exception ex)
            {
                _AB.EC.AddException(ex, this.ToString(), _AB.EC.Tools.GetCurrentMethodName());
            }
        }
        #endregion



        #region interface
        #region properties
        //public ObservableCollection<AllianceComparerListItem> AllianceCompareList
        //{
        //    get
        //    {
        //        return _ocAllianceCompareList;
        //    }
        //}

        public ArrayList KoordItems
        {
            get
            {
                return _aryKoordItems;
            }
        }

        public Boolean ExecuteViewCourt
        {
            get
            {
                return _fExecuteViewCourt;
            }
            set
            {
                _fExecuteViewCourt = value;
            }
        }

        public ICommand ShowMap
        {
            get
            {
                if(_rcShowMap == null)
                {
                    _rcShowMap = new RelayCommand(
                        param => this._ShowMap(),
                        param => this.CanShowMap);
                }
                return _rcShowMap;
            }
        }
        public Boolean CanShowMap
        {
            get
            {
                return _AB.UH.URLAllianceGetOtherInfo.URLMaybeValid;
            }
        }
        #endregion

        #region methods
        public void GenerateKoordItems()
        {
            _ExecuteURLs();
        }
        #endregion
        #endregion
    }
}
